// stores/user.js - 用户状态管理
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  // 状态
  state: () => ({
    user: null,
    isAuthenticated: false,
    token: null
  }),
  
  // getter
  getters: {
    // 获取用户名
    username: (state) => state.user?.username || '游客',
    // 检查是否登录
    isLoggedIn: (state) => state.isAuthenticated && !!state.token
  },
  
  // actions
  actions: {
    // 设置用户信息
    setUser(userData) {
      this.user = userData
      this.isAuthenticated = true
    },
    
    // 设置令牌
    setToken(token) {
      this.token = token
      // 将令牌存储在localStorage中
      if (token) {
        localStorage.setItem('auth_token', token)
      }
    },
    
    // 登出
    logout() {
      this.user = null
      this.isAuthenticated = false
      this.token = null
      localStorage.removeItem('auth_token')
    },
    
    // 初始化 - 检查本地存储的令牌
    init() {
      const token = localStorage.getItem('auth_token')
      if (token) {
        this.token = token
        // 这里通常会调用API验证令牌并获取用户信息
        // 简化示例，实际使用时应添加验证逻辑
        this.isAuthenticated = true
      }
    }
  }
}) 